<template>
  <div class="announcement-detail">
    <a-card>
      <template #title>
        <h2>{{ announcement.title }}</h2>
      </template>
      <template #extra>
        <a-space>
          <a-button @click="$router.back()">返回</a-button>
          <a-button type="primary" danger @click="handleDelete">删除</a-button>
        </a-space>
      </template>
      
      <a-descriptions bordered :column="2" style="margin-bottom: 20px">
        <a-descriptions-item label="发布人">
          {{ announcement.user?.username || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="发布时间">
          {{ announcement.time || '-' }}
        </a-descriptions-item>
      </a-descriptions>
      
      <a-divider />
      
      <div class="content" v-html="announcement.content"></div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { announcementAPI } from '@/api/announcement'
import type { Announcement } from '@/api/announcement'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const announcementId = Number(route.params.id)

const announcement = ref<Announcement>({
  id: announcementId,
  title: '',
  content: '',
  user: {
    id: 0,
    username: ''
  },
  time: ''
})

// 加载公告详情
const loadAnnouncement = async () => {
  if (!announcementId) {
    message.error('公告ID无效')
    router.back()
    return
  }
  
  loading.value = true
  try {
    const res = await announcementAPI.getAnnouncementDetail(announcementId)
    announcement.value = res.data
  } catch (error: any) {
    message.error('加载公告详情失败: ' + (error.response?.data?.message || error.message))
    router.back()
  } finally {
    loading.value = false
  }
}

// 删除公告
const handleDelete = () => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条公告吗？删除后无法恢复。',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await announcementAPI.deleteAnnouncement(announcementId)
        message.success('删除成功')
        router.push('/announcements/list')
      } catch (error: any) {
        message.error('删除失败: ' + (error.response?.data?.message || error.message))
      }
    }
  })
}

onMounted(() => {
  loadAnnouncement()
})
</script>

<style scoped>
.content {
  line-height: 1.8;
  font-size: 15px;
}

.content :deep(img) {
  max-width: 100%;
}
</style>
